package service

import (
	"log"
	commentModel "ozonTest/internal/domain/comments/model"
	"ozonTest/internal/domain/comments/service"
	postDAO "ozonTest/internal/domain/posts/dao"
	"ozonTest/internal/domain/posts/model"
)

type PostsService interface {
	CreatePost(post *model.Post) error
	GetPostByID(id int) (*model.Post, error)
	GetPostWithCommentsByID(id int) (*model.Post, []*commentModel.Comment, error)
	GetAllPosts() ([]model.Post, error)
	DeletePostByID(id int) error
	ChangeCommentsStatus(postUUID int, commentsAllowed bool) error
}

type postsService struct {
	postsRepo       postDAO.PostDAO
	commentsService service.CommentsService
}

func NewPostsService(postsRepo postDAO.PostDAO, commentsService service.CommentsService) PostsService {
	return &postsService{postsRepo: postsRepo, commentsService: commentsService}
}

func (s *postsService) CreatePost(post *model.Post) error {
	err := s.postsRepo.CreatePost(post)
	if err != nil {
		log.Printf("Failed to create post: %v", err)
		return err
	}
	return nil
}

func (s *postsService) GetPostByID(id int) (*model.Post, error) {
	post, err := s.postsRepo.GetPost(id)
	if err != nil {
		log.Printf("Failed to get post by ID %d: %v", id, err)
		return nil, err
	}
	return post, nil
}

func (s *postsService) GetPostWithCommentsByID(id int) (*model.Post, []*commentModel.Comment, error) {
	post, err := s.postsRepo.GetPost(id)
	if err != nil {
		log.Printf("Failed to get post by ID %d: %v", id, err)
		return nil, nil, err
	}
	comments, err := s.commentsService.GetAllPostComments(id)
	if err != nil {
		log.Printf("Failed to get comments for post ID %d: %v", id, err)
		return nil, nil, err
	}
	return post, comments, nil
}

func (s *postsService) GetAllPosts() ([]model.Post, error) {
	posts, err := s.postsRepo.GetAllPosts()
	if err != nil {
		log.Printf("Failed to get all posts: %v", err)
		return nil, err
	}
	return posts, nil
}

func (s *postsService) DeletePostByID(id int) error {
	err := s.postsRepo.DeletePost(id)
	if err != nil {
		log.Printf("Failed to delete post by ID %d: %v", id, err)
		return err
	}
	return nil
}

func (s *postsService) ChangeCommentsStatus(postUUID int, commentsAllowed bool) error {
	err := s.postsRepo.ChangeCommentsAllowed(postUUID, commentsAllowed)
	if err != nil {
		log.Printf("Failed to change comments status for post ID %d: %v", postUUID, err)
		return err
	}
	return nil
}
